package com.ruoyi.project.data.service.impl;

import java.math.BigDecimal;
import java.net.ConnectException;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.VideoUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.data.domain.ComparisonStatistics;
import com.ruoyi.project.data.domain.WeightRecordDistinguish;
import com.ruoyi.project.data.domain.WeightStationCamera;
import com.ruoyi.project.data.mapper.WeightStationCameraMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.data.mapper.WeightRecordMapper;
import com.ruoyi.project.data.domain.WeightRecord;
import com.ruoyi.project.data.service.IWeightRecordService;

/**
 * 称重记录Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-21
 */
@Service
public class WeightRecordServiceImpl implements IWeightRecordService
{
    @Autowired
    private WeightRecordMapper weightRecordMapper;
    @Autowired
    private WeightStationCameraMapper weightStationCameraMapper;

    /**
     * 查询称重记录
     *
     * @param id 称重记录ID
     * @return 称重记录
     */
    @Override
    public WeightRecord selectWeightRecordById(Long id)
    {
        return weightRecordMapper.selectWeightRecordById(id);
    }

    /**
     * 查询称重记录列表
     *
     * @param weightRecord 称重记录
     * @return 称重记录
     */
    @Override
    public List<WeightRecord> selectWeightRecordList(WeightRecord weightRecord)
    {
        return weightRecordMapper.selectWeightRecordList(weightRecord);
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public Map<String, Object> getCarDataByNo(Map<String, Object> param) {
        return weightRecordMapper.getCarDataByNo(param);
    }

    @Override
    public List<WeightRecordDistinguish> selectWeightRecordComparisonResults(WeightRecordDistinguish weightRecordDistinguish) {
        List<WeightRecordDistinguish>  list = weightRecordMapper.selectWeightRecordComparisonResults(weightRecordDistinguish);
        if(list != null && list.size() > 0){
            for(WeightRecordDistinguish distinguish : list){
                if("1".equals(distinguish.getCpsbjg())){
                    distinguish.setCpsbjg("否");
                }else{
                    distinguish.setCpsbjg("是");
                }
                if("1".equals(distinguish.getCpbdjg())){
                    distinguish.setCpbdjg("是");
                }else{
                    distinguish.setCpbdjg("否");
                }
            }
        }
        return list;
    }

    @Override
    public List<ComparisonStatistics> selectComparisonStatistics() {
        List<ComparisonStatistics> list = new ArrayList<>();
        List<Map<String, Object>> stationList = weightRecordMapper.selectStatisticsStation();
        if(stationList != null && stationList.size() > 0){
            for(Map<String, Object> stationMap : stationList){
                ComparisonStatistics comparisonStatistics = weightRecordMapper.selectComparisonStatistics(stationMap.get("stationCode").toString());
                if(comparisonStatistics != null){
                    comparisonStatistics.setStationName(stationMap.get("stationName").toString());
                    int dayNum = comparisonStatistics.getDayNum();
                    int dayTotal = comparisonStatistics.getDayTotal();
                    int nightNum = comparisonStatistics.getNightNum();
                    int nightYNum = comparisonStatistics.getNightYNum();
                    int nightTotal = comparisonStatistics.getNightTotal();
                    if(dayTotal > 0){
                        double f1 = new BigDecimal((float)(dayNum*100)/dayTotal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        String dayRate = f1 + "%";
                        comparisonStatistics.setDayRate(dayRate);
                    }else{
                        comparisonStatistics.setDayRate("0%");
                    }
                    if(nightTotal > 0){
                        double f1 = new BigDecimal((float)(nightNum*100)/nightTotal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        String nightRate = f1 + "%";
                        comparisonStatistics.setNightRate(nightRate);
                        double f2 = new BigDecimal((float)(nightYNum*100)/nightTotal).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        String nightYRate = f2 + "%";
                        comparisonStatistics.setNightYRate(nightYRate);
                    }else{
                        comparisonStatistics.setNightRate("0%");
                        comparisonStatistics.setNightYRate("0%");
                    }
                    list.add(comparisonStatistics);
                }
            }
        }
        return list;
    }

    @Override
    public AjaxResult getVideoPath(Long id) {
        //  获取称重详情
        WeightRecord weightRecord = weightRecordMapper.selectWeightRecordById(id);
        //  根据称重记录获取称重视频路径
        Map<String, Object> videoMap = weightRecordMapper.getVideoPath(weightRecord);
        if(videoMap != null){
            return AjaxResult.success(videoMap);
        }
        if(weightRecord.getStationCode().contains("320214")){
            if(weightRecord.getIsDown().equals("2") && StringUtils.isNotEmpty(weightRecord.getDownLabel())){
                videoMap = new HashMap<>();
                videoMap.put("videoPath", weightRecord.getDownLabel());
                return AjaxResult.success(videoMap);
            }
        } else {
            // 宜兴视频
            // 根据场站id获取相机编号
            WeightStationCamera weightStationCamera = new WeightStationCamera();
            weightStationCamera.setStationCode(weightRecord.getStationCode());
            weightStationCamera.setDeviceCode(weightRecord.getDeviceCode());
            weightStationCamera.setCameraType("6");
            String cameraCode = weightStationCameraMapper.selectCameraCode(weightStationCamera);
            if(cameraCode == null){
                return AjaxResult.error("暂无相机编号");
            }
            Date weightTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,weightRecord.getWeightTime());
            String startTime = DateUtils.addSecond(weightTime,-30);
            String endTime = DateUtils.addSecond(weightTime,30);
            if(weightRecord.getStationCode().contains("320282")){    // 宜兴
                try{
                    String json = VideoUtils.yxPlaybackVideo(cameraCode, startTime, endTime);
                    if(json == null || "".equals(json)){
                        return AjaxResult.error("调取视频失败");
                    }else{
                        JSONObject jsonObject = JSON.parseObject(json);
                        int code = jsonObject.getIntValue("code");
                        if(code == 0){
                            String url = jsonObject.getString("url");
                            videoMap = new HashMap<>();
                            videoMap.put("videoPath", url);
                            return AjaxResult.success(videoMap);
                        }else{
                            return AjaxResult.error("调取视频失败");
                        }
                    }
                }catch (Exception e)
                {
                    return AjaxResult.error("调取视频失败");
                }
            }else if(weightRecord.getStationCode().contains("320205") || weightRecord.getStationCode().contains("320281")
                    || weightRecord.getStationCode().contains("320206") || weightRecord.getStationCode().contains("320213")){     // 锡山/江阴/惠山/梁溪
                try{
                    String json = VideoUtils.playBackXs(cameraCode, startTime, endTime);
                    if(json == null || "".equals(json)){
                        return AjaxResult.error("调取视频失败");
                    }else{
                        JSONObject jsonObject = JSON.parseObject(json);
                        String code = jsonObject.getString("code");
                        if("0".equals(code)){
                            JSONObject data = jsonObject.getJSONObject("data");
                            String url = data.getString("url");
                            videoMap = new HashMap<>();
                            videoMap.put("videoPath", url);
                            return AjaxResult.success(videoMap);
                        }else{
                            return AjaxResult.error("调取视频失败");
                        }
                    }
                }catch (Exception e)
                {
                    return AjaxResult.error("调取视频失败");
                }
            }
        }
        return AjaxResult.error("暂无称重视频");
    }
}
